package service

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"lot_admin_api/api"
	"lot_admin_api/internal/consts"
	"lot_admin_api/internal/dao"
	"lot_admin_api/internal/model"
	"lot_admin_api/utility/paging"
	"lot_admin_api/utility/response"
)

type sStaff struct{}

var (
	insStaff = sStaff{}
)

func Staff() *sStaff {
	return &insStaff
}

// PhoneSearchCompany 通过员工手机id查询员工所在的公司列表
//func (s *sStaff) PhoneSearchCompany(ctx context.Context, phone string) (res []*model.PhoneStaffLoginRes, err error) {
//	r := g.RequestFromCtx(ctx)
//	// 获取该员工所属的所有的公司id
//	findStaffList, err := dao.LotStaff.Ctx(ctx).Fields("companyId").Where("staff_phone", phone).All()
//	if findStaffList == nil {
//		response.JsonExit(r, consts.HTTPInternalServer.Code(), "没有该员工的数据")
//	}
//	// 将员工所属的公司id转成searchCompanyIds g.slice
//	var searchCompanyIds []string
//	for i := range findStaffList.List() {
//		searchCompanyIds = append(searchCompanyIds, findStaffList[i]["company_id"].String())
//	}
//	// 查询员工所在的所有公司,返回公司列表
//	err = dao.LotCompany.Ctx(ctx).Where("id", searchCompanyIds).Scan(&res)
//	return res, err
//}

// GetIdStaffInfo 通过id 和公司id 获取员工详情
func (s *sStaff) GetIdStaffInfo(ctx context.Context, Id int64) (res *model.StaffInfoRes, err error) {
	r := g.RequestFromCtx(ctx)
	if err = dao.LotStaff.Ctx(ctx).Where("id", Id).Scan(&res); res == nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "没有当前员工")
	}
	// 查询员工公司
	if err = dao.LotCompany.Ctx(ctx).Where("id", res.CompanyId).Scan(&res.CompanyInfo); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "没有当前公司")
	}
	// 查询员工部门
	if res.DepartmentId != 0 {
		err = dao.LotDepartment.Ctx(ctx).Where("id", res.DepartmentId).Scan(&res.DepartmentInfo)
	}
	// 查询员工角色
	if res.RoleId != 0 {
		err = dao.LotRole.Ctx(ctx).Where("id", res.RoleId).Scan(&res.RoleInfo)
	}
	// 查询员工权限
	if res.AuthInfo != nil {
		err = dao.LotAuth.Ctx(ctx).Where("id", res.RoleInfo.AuthIds).Scan(&res.AuthInfo)
	}
	return res, err
}

// StaffList 获取员工列表
func (s *sStaff) StaffList(ctx context.Context, req *api.StaffListReq) (res *model.StaffListPageRes, err error) {
	staffList := make([]*model.StaffListInfoRes, 0)
	// 获取分页偏移量
	startNum, endNum := paging.Paging(req.Paging)
	condition := g.Map{
		"staff_name like ?":  "%" + req.StaffName + "%",  // 模糊查询名字
		"staff_phone like ?": "%" + req.StaffPhone + "%", // 模糊查询手机
		"staff_code":         req.StaffCode,
		"department_id":      req.DepartmentId,
		"role_id":            req.RoleId,
		"company_id":         req.CompanyId,
	}
	// 获取员工列表
	err = dao.LotStaff.Ctx(ctx).OmitEmpty().WithAll().Where(condition).Limit(startNum, endNum).Scan(&staffList)

	// 获取总条数
	countInfo, err := dao.LotStaff.Ctx(ctx).OmitEmpty().Where(condition).Count()
	putCount := paging.PutCount(req.Paging, countInfo)
	res = &model.StaffListPageRes{
		List:    staffList,
		PutPage: *putCount,
	}
	return res, err
}

// AddStaff 添加员工
func (s *sStaff) AddStaff(ctx context.Context, req *api.AddStaffReq) (id int64, err error) {
	//staffInfo := cache.StaffInfo(ctx)
	r := g.RequestFromCtx(ctx)
	//req.CompanyId = staffInfo.CompanyId
	searchInfo := g.Map{
		"company_id":  req.CompanyId,
		"staff_phone": req.StaffPhone,
	}
	if searchStaff, _ := dao.LotStaff.Ctx(ctx).Where(searchInfo).One(); searchStaff != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "该手机号已被注册")
	}

	saveInfo, err := dao.LotStaff.Ctx(ctx).OmitEmpty().Save(&req)
	id, _ = saveInfo.LastInsertId()
	return id, err
}

// UpdateStaff 更新员工
func (s *sStaff) UpdateStaff(ctx context.Context, req *api.UpdateStaffReq) (id int64, err error) {
	//staffInfo := cache.StaffInfo(ctx)
	r := g.RequestFromCtx(ctx)
	//req.CompanyId = staffInfo.CompanyId
	_ = s.SearchStaff(ctx, req.Id)
	searchInfo := g.Map{
		"company_id":  req.CompanyId,
		"staff_phone": req.StaffPhone,
	}
	if searchStaff, _ := dao.LotStaff.Ctx(ctx).Where(searchInfo).All(); searchStaff.Len() > 1 {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "已有员工使用该手机号")
	}
	saveInfo, err := dao.LotStaff.Ctx(ctx).Data(&req).OmitEmpty().Where("id", req.Id).Update()
	id, _ = saveInfo.LastInsertId()
	return id, err
}

// DeleteStaff 删除员工
func (s *sStaff) DeleteStaff(ctx context.Context, req *api.DeleteStaffReq) (id int64, err error) {
	_ = s.SearchStaff(ctx, req.Id)
	_, err = dao.LotStaff.Ctx(ctx).Where("id", req.Id).Delete()
	return req.Id, err
}

// AllocationStaff 调拨员工
func (s *sStaff) AllocationStaff(ctx context.Context, req *api.AllocationStaffReq) (id int64, err error) {
	_ = s.SearchStaff(ctx, req.Id)                              // 查询是否有当前员工
	_, _ = Department().SearchDepartment(ctx, req.DepartmentId) // 查询是否有当前部门
	// 更新部门
	_, err = dao.LotStaff.Ctx(ctx).Fields("department_id").Data(&req).Where("id", req.Id).Update()
	return req.Id, err
}

// SearchStaff 查询当前用户
func (s *sStaff) SearchStaff(ctx context.Context, Id int64) (searchOne *model.StaffInfo) {
	//staffInfo := cache.StaffInfo(ctx)
	r := g.RequestFromCtx(ctx)
	//CompanyId := staffInfo.CompanyId
	// 组装搜索条件
	searchCondition := g.Map{
		"id": Id,
		//"company_id": CompanyId,
	}
	if _ = dao.LotStaff.Ctx(ctx).Where(searchCondition).Scan(&searchOne); searchOne == nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "没有当前员工")
	}
	return searchOne
}
